package cn.enilu.flash.mobile.controller;

import cn.enilu.flash.bean.entity.shop.Order;
import cn.enilu.flash.bean.entity.shop.ShopUser;
import cn.enilu.flash.bean.enumeration.shop.OrderEnum;
import cn.enilu.flash.bean.vo.front.Rets;
import cn.enilu.flash.service.zhifu.AlipayService;
import cn.enilu.flash.service.zhifu.WeixinPayService;
import cn.enilu.flash.service.zhifu.config.AlipayProperties;
import cn.enilu.flash.service.shop.OrderService;
import cn.enilu.flash.service.shop.ShopUserService;
import cn.enilu.flash.utils.StringUtil;
import cn.enilu.flash.web.controller.BaseController;
import com.github.binarywang.wxpay.bean.notify.WxPayNotifyResponse;
import com.github.binarywang.wxpay.bean.notify.WxPayRefundNotifyResult;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：enilu
 * @date ：Created in 2020/3/17 20:15
 */
@RestController
@RequestMapping("/pay")
public class PayController extends BaseController {
    @Autowired
    private ShopUserService shopUserService;
    @Autowired
    private WeixinPayService weixinPayService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private AlipayProperties alipayProperties;
    @Autowired
    private AlipayService alipayService;

    @ApiOperation("支付宝电脑网站支付")
    @RequestMapping(value = "alipay/pay", method = RequestMethod.GET)
    public void pay(@RequestParam("orderSn")String orderSn, HttpServletResponse response) throws IOException {
        ShopUser user = shopUserService.getCurrentUser();
        Order order = orderService.getByOrderSn(orderSn);
        String payHtml = alipayService.pay(user,order);

        response.setContentType("text/html;charset=" + alipayProperties.getCharset());
        response.getWriter().write(payHtml);
        response.getWriter().flush();
        response.getWriter().close();
    }

    @ApiOperation("支付宝手机网站支付")
    @RequestMapping(value = "alipay/webPay", method = RequestMethod.GET)
    public void webPay(@RequestParam("orderSn")String orderSn, HttpServletResponse response) throws IOException {
        ShopUser user = shopUserService.getCurrentUser();
        Order order = orderService.getByOrderSn(orderSn);
        String payHtml = alipayService.webPay(user,order);

        response.setContentType("text/html;charset=" + alipayProperties.getCharset());
        response.getWriter().write(payHtml);
        response.getWriter().flush();
        response.getWriter().close();
    }

    @ApiOperation(value = "支付宝异步回调",notes = "必须为POST请求，执行成功返回success，执行失败返回failure")
    @RequestMapping(value = "alipay/notify", method = RequestMethod.POST)
    public Object notify(HttpServletRequest request){
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
        }
        String result = alipayService.notify(params);
        return Rets.success(result);
    }

    @ApiOperation(value = "支付宝统一收单线下交易查询",notes = "订单支付成功返回：TRADE_SUCCESS")
    @RequestMapping(value = "alipay/query", method = RequestMethod.GET)
    @ResponseBody
    public Object query(String outTradeNo, String tradeNo){
        String result = alipayService.query(outTradeNo,tradeNo);
        return Rets.success(result);
    }


    @RequestMapping(value = "wx/prepare",method = RequestMethod.POST)
    public Object wxPrepare(@RequestParam("orderSn")String orderSn){
        ShopUser user = shopUserService.getCurrentUser();
        if(StringUtil.isEmpty(user.getWechatOpenId())){
            return Rets.failure("非微信用户");
        }
        Order order = orderService.getByOrderSn(orderSn);
        WxPayMpOrderResult wxOrder = weixinPayService.prepare(user,order);
        if(wxOrder!=null) {
            return Rets.success(wxOrder);
        }
        return Rets.failure("数据准备异常，请刷新页面");
    }

    /**
     * 微信支付回调
     * @return
     */
    @RequestMapping(value = "wx/notify",method = RequestMethod.POST)
    public Object wxNotify(){
        String  msg = weixinPayService.resultNotify();
        return msg;
    }


    @ApiOperation(value = "发起退款")
    @PostMapping("wx/refund")
    public Object refund(@RequestParam("orderSn")String orderSn) throws WxPayException {
        Order order = orderService.getByOrderSn(orderSn);
        return weixinPayService.refund(order);
    }
    @ApiOperation(value = "退款回调通知处理")
    @PostMapping("wx/refundNotify")
    public String parseRefundNotifyResult(@RequestBody String xmlData) throws WxPayException {
        String  msg = weixinPayService.refundNotify(xmlData);
        return msg;
    }


    /**
     * 查询支付结果
     * @param orderSn
     * @return
     */
    @RequestMapping(value = "queryResult/{orderSn}",method = RequestMethod.GET)
    public Object wxQuery(@PathVariable("orderSn") String orderSn){
        Order order = orderService.getByOrderSn(orderSn);
        Boolean payResult = OrderEnum.PayStatusEnum.UN_SEND.getId().equals(order.getPayStatus())
                && OrderEnum.PayStatusEnum.UN_SEND.getId().equals(order.getStatus());
        return Rets.success(payResult);
    }
}
